package com.example.a7822.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.linphone.LinphoneManager;
import org.linphone.LinphonePreferences;
import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneCoreException;


public class MainActivity extends YTLauncherActivity {

    private Handler mhandler;
    private EditText username;
    private EditText password;
    private EditText callUsername;
    //    private EditText domainEditText;
    private Button login;
    private Button call;
    private ServiceWaitThread mThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mThread = new ServiceWaitThread();
        mhandler = new Handler();
        username = (EditText) findViewById(R.id.sipId);
        password = (EditText) findViewById(R.id.sipPassword);
        callUsername = (EditText) findViewById(R.id.callUsername);
//        domainEditText=(EditText) findViewById(R.id.domain);
        login = (Button) findViewById(R.id.login);
        call = (Button) findViewById(R.id.callBtn);
        call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callOutgoing(callUsername.getText().toString());
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mThread.start();
            }
        });
    }

    // 开启线程登录
    private void syncAccount(String username, String password, String domain) {

        LinphonePreferences mPrefs = LinphonePreferences.instance();
        if (mPrefs.isFirstLaunch()) {
            mPrefs.setAutomaticallyAcceptVideoRequests(true);
//            mPrefs.setInitiateVideoCall(true);
            mPrefs.enableVideo(true);
        }
        int nbAccounts = mPrefs.getAccountCount();
        if (nbAccounts > 0) {
            String nbUsername = mPrefs.getAccountUsername(0);
            if (nbUsername != null && !nbUsername.equals(username)) {
                mPrefs.deleteAccount(0);
                saveNewAccount(username, password, domain);
            }
        } else {
            saveNewAccount(username, password, domain);
            mPrefs.firstLaunchSuccessful();
        }
    }

    private void saveNewAccount(String username, String password, String domain) {
        LinphonePreferences.AccountBuilder builder = new LinphonePreferences.AccountBuilder(LinphoneManager.getLc())
                .setUsername(username)
                .setDomain(domain)
                .setPassword(password)
                .setDisplayName("displayName")
                .setTransport(LinphoneAddress.TransportType.LinphoneTransportTcp);

        try {
            builder.saveNewAccount();
            Toast.makeText(this,"登陆成功",Toast.LENGTH_LONG).show();
        } catch (LinphoneCoreException e) {
            Log.e("MainActivity", e.toString());
        }
    }

    private class ServiceWaitThread extends Thread {
        public void run() {
            while (!YTCallService.isReady()) {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    throw new RuntimeException("waiting thread sleep() has been interrupted");
                }
            }
            mhandler.post(new Runnable() {
                @Override
                public void run() {
                    syncAccount(username.getText().toString(), password.getText().toString(), "120.26.39.36");
                }
            });
            mThread = null;
        }
    }

    private void callOutgoing(String number) {
        try {
            if (!LinphoneManager.getInstance().acceptCallIfIncomingPending()) {
                String to = String.format("sip:%s@%s", number, "120.26.39.36");
                LinphoneManager.getInstance().newOutgoingCall(to, "displayName");

                startActivity(new Intent()
                        .setClass(this, YTLinphoneActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }
        } catch (LinphoneCoreException e) {
            LinphoneManager.getInstance().terminateCall();
        }
    }
}
